﻿using System;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model.Db.Hr.Bill;
using Microsoft.EntityFrameworkCore;

namespace HengTong.ViewModel.Daily.SysDailyCompOffRequestBillVms;

public partial class SysDailyCompOffRequestBillBatchVm
{
    /// <summary>
    /// 批量删除调休申请和关联的中间表数据
    /// </summary>
    public async Task<bool> DoBatchDeleteAsync()
    {
        if (Ids == null || !Ids.Any())
        {
            MSD.AddModelError(" ", "请选择要删除的调休申请");
            return false;
        }

        var transaction = await DC.Database.BeginTransactionAsync();
        try
        {
            // 将string ID转换为Guid列表
            var ids = Ids.Select(x => Guid.Parse(x)).ToList();

            // 先删除中间表关联数据
            await DC.Set<SysCompOffOvertimeLink>()
                .Where(link => ids.Contains(link.CompOffRequestBillId))
                .ExecuteDeleteAsync();

            // 删除主表数据
            await DC.Set<SysDailyCompOffRequestBill>()
                .Where(bill => ids.Contains(bill.ID))
                .ExecuteDeleteAsync();

            await DC.SaveChangesAsync();
            await transaction.CommitAsync();
            return true;
        }
        catch (Exception e)
        {
            await transaction.RollbackAsync();
            MSD.AddModelError(" ", $"批量删除异常：{e.Message}");
            return false;
        }
        finally
        {
            await transaction.DisposeAsync();
        }
    }
}